<template>
  <div class="product-add">
    <el-card class="product-box" shadow="hover">
      <div slot="header" style="text-align: left">
        <i class="el-icon-circle-plus-outline" />
        <span>添加商品</span>
      </div>
      <div class="info-box">
        <el-form class="product-form" :model="productForm" :inline="true" :rules="productRules" ref="productForm">

          <el-form-item label="商品名称：" prop="product_name" style="width: 100%">
            <el-input size="small" v-model="productForm.product_name" style="width: 300px"
              placeholder="请选择商品名称"></el-input>
          </el-form-item>

          <el-form-item label="商品分别：" prop="type_id" style="width: 45%">
            <el-select size="small" v-model="productForm.type_id" filterable placeholder="请选择类别">
              <el-option v-for="(item, index) in productTypeInfo" :key="index" :value="item.type_id">{{ item.type_name }}
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="商品分类：" prop="product_sort" style="width: 45%">
            <el-select size="small" v-model="productForm.product_sort" filterable placeholder="请选择类别">
              <el-option label="蛋糕" value="蛋糕">
                蛋糕
              </el-option>
              <el-option label="下午茶" value="下午茶">下午茶</el-option>
              <el-option label="面包" value="面包">面包</el-option>
              <el-option label="精选食材" value="精选食材">精选食材</el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="商品蜜度：" prop="product_sweetness" style="width: 45%">
            <el-input min=0 size="small" type='number' v-model="productForm.product_sweetness"
              placeholder="商品蜜度"></el-input>
          </el-form-item>

          <el-form-item label="商品芝度：" prop="product_cheese" style="width: 45%">
            <el-input min=0 size="small" type='number' v-model="productForm.product_cheese" placeholder="商品芝度"></el-input>
          </el-form-item>

          <el-form-item label="商品进价：" prop="in_price" style="width: 45%;">
            <el-input min=0 size="small" max="100" type='number' v-model="productForm.in_price"
              placeholder="商品进价"></el-input>
          </el-form-item>

          <el-form-item label="商品售价：" prop="out_price" style="width: 45%;">
            <el-input min=0 size="small" type='number' v-model="productForm.out_price" placeholder="商品售价"></el-input>
          </el-form-item>
          <el-form-item label="商品库存：" prop="product_stock" style="width: 45%;">
            <el-input-number size="small" :min=0 :max=1000 v-model="productForm.product_stock"
              placeholder="商品库存"></el-input-number>
          </el-form-item>

          <el-form-item label="商品介绍：" prop="product_describe">
            <el-input type="textarea" class="product-desc" size="small" show-word-limit
              :autosize="{ minRows: 1, maxRows: 4 }" v-model="productForm.product_describe" placeholder="商品描述"></el-input>
          </el-form-item>

          <el-form-item label="商品状态：" style="width: 100%;height: 30px">
            <el-form-item label="上架" prop="is_sale" style="margin-right:50px">
              <el-switch v-model="productForm.is_sale"></el-switch>
            </el-form-item>
            <el-form-item label="新品" prop="is_new">
              <el-switch v-model="productForm.is_new"></el-switch>
            </el-form-item>
          </el-form-item>
          <div style="display: flex; justify-content: space-between;">

            <el-form-item label="商品图片1：" prop="product_url1" style="width: 45%;">
              <el-upload class="product-upload" action="http://127.0.0.1:3000/api/productImg" :on-success="uploadSuccess1"
                :on-exceed="handleExceed" :drag="true" list-type="picture" :limit="1" :auto-upload="false"
                style="display: flex;justify-content: center;align-items: center;height: 140px;width: 160px"
                ref="upload1">
                <el-image v-if="productForm.product_url1" :src="productForm.product_url1"
                  style="height: 140px;width: 160px"></el-image>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>

            <el-form-item label="商品图片2：" prop="product_url2" style="width: 45%;">
              <el-upload class="product-upload" action="http://127.0.0.1:3000/api/productImg" :on-exceed="handleExceed"
                :on-success="uploadSuccess2" :drag="true" list-type="picture" :limit="1" :auto-upload="false"
                style="display: flex;justify-content: center;align-items: center;height: 140px;width: 160px"
                ref="upload2">
                <el-image v-if="productForm.product_url2" :src="productForm.product_url2"
                  style="height: 140px;width: 160px">
                </el-image>
                <i v-else class="el-icon-plus avatar-uploader-icon">
                </i>
              </el-upload>
            </el-form-item>
          </div>
          <el-form-item style="width:100%;text-align: center;">
            <el-button @click="submitForm('productForm')" type="primary" style="margin: 0 55px">添加商品</el-button>
            <el-button @click="resetForm('productForm')" style="margin: 0 55px">取消重置</el-button>
          </el-form-item>
        </el-form>



      </div>
    </el-card>
  </div>
</template>

<script>
import { getType, Product, updateProduct } from '@/api/index';
export default {
  name: 'KodaiProductAdd',

  data () {
    return {
      productForm: {
        product_no: '',
        product_name: '',
        explain_id: '',
        type_id: '',
        product_describe: '',
        in_price: 0,
        out_price: 0,
        product_stock: 50,
        is_new: true,
        is_sale: true,
        product_url1: '',
        specs_id: '',
        product_url2: '',
        product_sweetness: '',
        product_cheese: '',
        product_sort: '',
        product_id: ''
      },
      productRules: {
        product_name: [{ required: true, message: '请填写商品名称', trigger: 'blur' },
        { min: 1, max: 30, message: '名称长度不允许超过 30 个字符', trigger: 'blur' }],
        productBrand: [{ required: true, message: '请选择商品品牌', trigger: 'blur' }],
        productType: [{ required: true, message: '请选择商品分类', trigger: 'blur' }],
        product_describe: [{ required: true, message: '请填写商品介绍', trigger: 'blur' },
        { min: 1, max: 100, message: '名称长度不允许超过 100 个字符', trigger: 'blur' }],
        product_describe: [{ required: true, message: '请填写商品介绍', trigger: 'blur' },
        { min: 1, max: 100, message: '名称长度不允许超过 100 个字符', trigger: 'blur' }],
        product_sweetness: [{ required: true, min: 1, max: 100, message: '名称长度不允许超过 100 个字符', trigger: 'blur' }],
        product_cheese: [{ required: true, min: 1, max: 100, message: '名称长度不允许超过 100 个字符', trigger: 'blur' }],
        product_sort: [{ required: true }],
        in_price: [{ required: true, min: 1, max: 100, message: '名称长度不允许超过 100 个字符', trigger: 'blur' }],
        out_price: [{ required: true, min: 1, max: 100, message: '名称长度不允许超过 100 个字符', trigger: 'blur' }],
        type_id: [{ required: true }],
        product_stock: [{ required: true }]
      },
      productTypeInfo: [],
      productForms:false
    }

  },

  mounted () {
    getType().then(res => {
      this.productTypeInfo = res.data.data
    })
    if (JSON.parse(this.$route.query.data)) {
     this.productForms=true
      this.productForm = JSON.parse(this.$route.query.data)
    }
  },

  methods: {
    // 上传图片函数
    uploadSuccess1 (res, file) {
      if (res.code === 200) {
        this.showMessage.call(this, 'success', "商品图片上传成功！");
        this.productForm.product_url1 = res.url;
        this.$refs['upload1'].clearFiles();
      } else {
        this.showMessage.call(this, 'error', "商品图片上传失败！");
      }
    }, uploadSuccess2 (res, file) {
      if (res.code === 200) {
        this.showMessage.call(this, 'success', "商品图片上传成功！");
        this.productForm.product_url2 = res.url;
        this.$refs['upload1'].clearFiles();
      } else {
        this.showMessage.call(this, 'error', "商品图片上传失败！");
      }
    },
    // 文件数量过多时提醒
    handleExceed () {
      this.showMessage.call(this, 'error', "最多支持1个附件上传");
    },
    //提交表单
    submitForm (productForm) {
      this.$refs[productForm].validate((valid) => {
        if (valid) {
          if (this.productForms) {
            this.productForm.is_new = this.productForm.is_new ? '1' : '0'
            this.productForm.is_sale = this.productForm.is_sale ? '1' : '0'
            this.$refs.upload1.submit();
            this.$refs.upload2.submit();
            setTimeout(() => {
              updateProduct(this.productForm).then(res => {
                if (res.data.code === 200) {
                  this.$notify({ title: '成功', message: this.productForms.product_name + '\t修改成功', type: 'success' });
                  this.resetForm('productForm')
                  this.productForms=false
                }
              }).catch(() => {
                this.$notify({ title: '错误', type: 'error' });
              });
            }, 2000);

          } else {
            this.$refs.upload1.submit();
            this.$refs.upload2.submit();
            this.productForm.is_new = this.productForm.is_new == true ? '1' : '0'
            this.productForm.is_sale = this.productForm.is_sale == true ? '1' : '0'
            this.productForm.explain_id = `E${this.$getDateNow()}`
            this.productForm.specs_id = `S${this.$getDateNow()}`
            this.productForm.product_no = `P${this.$getDateNow()}`
            this.productForm.product_id = `${this.$getDateNow()}`
            let loading = this.$loading({ lock: true, text: "数据提交中", background: "rgba(255,255,255,0.5)" });
            setTimeout(() => {
              Product(this.productForm).then(res => {
                if (res.data.code === 200) {
                  loading.close();
                  this.dialogFormVisible = false;
                  this.$router.go(0)
                  this.$notify({ title: '成功', message: this.productForm.product_name + '\t商品添加成功', type: 'success' });
                }
              }).catch(() => {
                loading.close();
                this.$message.error('提交失败')
              });
            }, 1000)
          }
        } else {
          return false;
        }
      });
    },
    //重置表单
    resetForm (productForm) {
      // this.getDateNow();
      this.$refs[productForm].resetFields();
    },
  }
}
</script>

<style lang="scss" scoped>
.product-add {
  margin: 10px auto;
  padding: 0;
  min-height: 100%;
  user-select: none;
  min-width: 1226px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f9f9f9;
}


.product-add .product-box {
  height: 700px;
  width: 90%;
}

.product-add .info-box {
  height: 600px;
  border: 1px solid #dddedf;
}

.product-add .product-form {
  width: 80%;
  height: 560px;
  margin: 25px auto 0;
  text-align: left;
  position: relative;
}

.product-add .product-form .el-form-item {
  margin-bottom: 10px;
}

.product-add .product-upload ::v-deep .el-upload-dragger {
  height: 80px !important;
  width: 160px !important;
  display: flex;
  justify-content: center;
  align-items: center;
}

.product-add .product-desc ::v-deep .el-textarea__inner {
  min-width: 160px;
  //  height: 145px !important;
}

.product-add .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.product-add .product-form .el-form-item__label {
  width: 94px;
}
</style>